package com.qyhl.shop.shop.gift;

import android.os.Bundle;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopGiftListBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class ShopGiftListFragment extends BaseFragment implements ShopGiftListContract.ShopGiftListView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private ShopGiftListPresenter mPresenter;

    private CommonAdapter<ShopGiftListBean> commonAdapter;

    private List<ShopGiftListBean> mDataList = new ArrayList<>();

    private int page = 1;

    private int range;

    public void setRange(int range) {
        this.range = range;
    }

    public static ShopGiftListFragment newInstance(int range) {
        ShopGiftListFragment fragment = new ShopGiftListFragment();
        fragment.setRange(range);
        return fragment;
    }


    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .init();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.shop_fragment_gift_list, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);
        BusFactory.getBus().register(this);
        mPresenter = new ShopGiftListPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        recycleView.setAdapter(commonAdapter = new CommonAdapter<ShopGiftListBean>(getContext(), R.layout.shop_item_gift_list, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShopGiftListBean bean, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(ShopGiftListFragment.this)
                        .load(bean.getCoverPicUrl())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);

                holder.setText(R.id.title, bean.getGiftName());

                if (bean.getPrice() == 0) {
                    holder.setText(R.id.price, "免费");
                } else {
                    holder.setText(R.id.price, "¥" + bean.getPrice());
                }

                holder.setText(R.id.quantity, "x1");

                TextView totalPrice = holder.getView(R.id.total_price);
                SpanUtils spanUtils = new SpanUtils(getContext());
                spanUtils.append("¥").setSpans(new TextAppearanceSpan(getContext(), R.style.shop_gift_price_three))
                        .append(bean.getPrice() + "").setSpans(new TextAppearanceSpan(getContext(), R.style.shop_gift_price_one));

                totalPrice.setText(spanUtils.create());
                TextView shopName = holder.getView(R.id.shop_name);
                if (bean.getShopId() == 0) {
                    holder.setText(R.id.shop_name, bean.getOrganizer());
                    shopName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                } else {
                    holder.setText(R.id.shop_name, bean.getShopName());
                    shopName.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(getContext(), R.drawable.user_arrow_right_gray), null);
                }

                switch (bean.getPhase()) {
                    case 1:
                        holder.setText(R.id.status, "等待付款");
                        holder.setTextColorRes(R.id.status, R.color.shop_common_red);
                        holder.setVisible(R.id.pay_btn, true);
                        break;
                    case 2:
                        holder.setText(R.id.status, "待使用");
                        holder.setTextColorRes(R.id.status, R.color.shop_common_red);
                        holder.setVisible(R.id.pay_btn, false);
                        break;
                    case 3:
                        holder.setText(R.id.status, "已兑换");
                        holder.setTextColorRes(R.id.status, R.color.shop_common_message);
                        holder.setVisible(R.id.pay_btn, false);
                        break;
                    case 4:
                        holder.setText(R.id.status, "已失效");
                        holder.setTextColorRes(R.id.status, R.color.shop_common_message);
                        holder.setVisible(R.id.pay_btn, false);
                        break;
                    case 5:
                        holder.setText(R.id.status, "已取消");
                        holder.setTextColorRes(R.id.status, R.color.shop_common_message);
                        holder.setVisible(R.id.pay_btn, false);
                        break;
                }

                holder.setOnClickListener(R.id.pay_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ARouter.getInstance()
                                .build(ARouterPathConstant.SHOP_GIFT_ORDER)
                                .withSerializable("id", bean.getUserGiftId())
                                .withSerializable("isMine", true)
                                .navigation();
                    }
                });

                holder.setOnClickListener(R.id.shop_name, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (bean.getShopId() != 0) {
                            ARouter.getInstance()
                                    .build(ARouterPathConstant.SHOP_SHOP_DETAIL)
                                    .withInt("shopId", bean.getShopId())
                                    .navigation();
                        }
                    }
                });
            }
        });

        mPresenter.getList(page, range);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getList(page, range);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getList(page, range);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(page, range);
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                if (mDataList.get(i).getPhase() == 1) {
                    ARouter.getInstance()
                            .build(ARouterPathConstant.SHOP_GIFT_ORDER)
                            .withSerializable("id", mDataList.get(i).getUserGiftId())
                            .withSerializable("isMine", true)
                            .navigation();
                } else {
                    ARouter.getInstance()
                            .build(ARouterPathConstant.SHOP_GIFT_DETAIL)
                            .withInt("id", mDataList.get(i).getUserGiftId())
                            .withBoolean("isCancel", mDataList.get(i).getPhase() == 5)
                            .navigation();
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    @Override
    public void setList(List<ShopGiftListBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (page != 1) {
            refresh.finishLoadMore();
        } else {
            if (beanList == null) {
                setError("暂无任何礼品!");
                return;
            }
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void doRefresh(Event.OrderRefresh event) {
        if (event != null) {
            if (event.getUserGiftId() != 0) {
                if (range == 1) {
                    for (int i = 0; i < mDataList.size(); i++) {
                        if (mDataList.get(i).getUserGiftId() == event.getUserGiftId()) {
                            commonAdapter.notifyItemRemoved(i);
                        }
                    }
                } else {
                    page = 1;
                    mPresenter.getList(page, range);
                }
            } else {
                page = 1;
                mPresenter.getList(page, range);
            }
        }
    }

    @Override
    public void setError(String msg) {
        if (page != 1) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {

            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }
}
